/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-05-17     fanlulin       the first version
 */
#include "uart.h"
#define SAMPLE_UART_NAME       "uart1"      /* 串口设备名称 */

/* 用于接收消息的信号量 */
static struct rt_semaphore rx_sem;

static rt_device_t serial;

/*
 * 信号量的使用情况
 * 信号量在接收到数据值释放，然后
 * 信号量调用函数显示后再阻塞
 */


/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

static void serial_thread_entry(void *parameter)
{
    char ch;

    while (1)
    {
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }
        if(ch=='0'){
            rt_pin_write(LED_PIN1, PIN_HIGH);
            rt_pin_write(LED_PIN2, PIN_HIGH);
            rt_pin_write(LED_PIN3, PIN_HIGH);

        }
        else if (ch=='1') {
            rt_pin_write(LED_PIN1, PIN_LOW);
        }
        else if (ch=='2') {
            rt_pin_write(LED_PIN2, PIN_LOW);
        }
        else if (ch=='3') {
            rt_pin_write(LED_PIN3, PIN_LOW);
        }
        /* 读取到的数据通过串口错位输出 */
        rt_device_write(serial, 0, &ch, 1);
    }
}

int serial_thread()
{

    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX];
    char str[] = "hello RT-Thread!\r\n";

    rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);


    /* 查找串口设备 */
    serial = rt_device_find(uart_name);
    if (!serial)
    {
        rt_kprintf("find %s failed!\n", uart_name);
        return RT_ERROR;
    }

    /* 初始化信号量 */
    //参数：1.信号量句柄  2.信号量名称  3.信号量初始值  4.线程在信号量上的等待方式（先进先出RT_IPC_FLAG_FIFO，优先级等待RT_IPC_FLAG_PRIO）
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);


    /* 以读写及中断接收方式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX);

    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);

    /* 发送字符串 */
    /*从位置0开始发送str字符串*/
    rt_device_write(serial, 0, str, (sizeof(str) - 1));

    /* 创建 serial 线程 */
    rt_thread_t uart = rt_thread_create("serial",
                                          serial_thread_entry, RT_NULL,
                                          THREAD_STACK_SIZE,
                                          THREAD_PRIORITY, THREAD_TIMESLICE);
    /* 创建成功则启动线程 */
    if (uart != RT_NULL)
    {
        rt_thread_startup(uart);
        rt_kprintf("serial thread start successfully\r\n");
    }
    else
    {
        ret = RT_ERROR;
        rt_kprintf("serial thread start failed\r\n");
    }

    return ret;
}
/* 导出到 msh 命令列表中 */
//MSH_CMD_EXPORT(uart_sample, uart device sample);
